package storage

import (
	"sync"
)

type MemoryStorage struct {
	mu    sync.RWMutex
	urls  map[string]string // shortCode -> longURL
	codes map[string]string // longURL -> shortCode
}

func NewMemoryStorage() *MemoryStorage {
	return &MemoryStorage{
		urls:  make(map[string]string),
		codes: make(map[string]string),
	}
}

func (s *MemoryStorage) Save(longURL, shortCode string) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	if _, exists := s.urls[shortCode]; exists {
		return ErrURLExists
	}

	s.urls[shortCode] = longURL
	s.codes[longURL] = shortCode
	return nil
}

func (s *MemoryStorage) Get(shortCode string) (string, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	longURL, exists := s.urls[shortCode]
	if !exists {
		return "", ErrURLNotFound
	}
	return longURL, nil
}

func (s *MemoryStorage) Exists(longURL string) (string, bool) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	shortCode, exists := s.codes[longURL]
	return shortCode, exists
}